package com.atguigu.myjuc.mythread.day2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
//a->b->c三个线程依次通信
class paper {
    int flag = 1;
    final ReentrantLock lock = new ReentrantLock();
    final Condition condition1 = lock.newCondition();
    final Condition condition2 = lock.newCondition();
    final Condition condition3 = lock.newCondition();

    public void printFive() throws InterruptedException {

        lock.lock();
        try {
            while (flag != 1) {

                condition1.await();
            }

            condition2.signal();
            flag = 2;
            for (int i = 0; i < 5; i++) {
                System.out.println("a");


            }
        } finally {
            lock.unlock();
        }
    }

    public void printTen() {
        lock.lock();
        try {
            while (flag != 2) {

                condition2.await();
            }

            condition3.signal();
            flag = 3;
            for (int i = 0; i < 10; i++) {
                System.out.println("b");


            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void printFifTeen() {
        lock.lock();
        try {
            while (flag != 3) {

                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            condition1.signal();
            flag = 1;
            for (int i = 0; i < 15; i++) {
                System.out.println("c");


            }
        } finally {
            lock.unlock();
        }
    }
}
    public class ThreadOrderAddress {


        public static void main(String[] args) {


            paper paper = new paper();
            new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    try {
                        paper.printFive();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

            }, "a").start();
            new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    paper.printTen();
                }

            }, "b").start();
            new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    paper.printFifTeen();
                }

            }, "c").start();

        }

    }

